package cn.community.system.service.impl;

import cn.community.system.domain.Association;
import cn.community.system.domain.Member;
import cn.community.system.domain.MemberVo;
import cn.community.system.exception.LogicException;
import cn.community.system.mapper.AssociationMapper;
import cn.community.system.mapper.MemberMapper;
import cn.community.system.mapper.MemberVoMapper;
import cn.community.system.mapper.RoleMapper;
import cn.community.system.query.AssociationQuery;
import cn.community.system.query.QueryObject;
import cn.community.system.service.IAssociationService;
import cn.community.system.util.AssertUtils;
import cn.community.system.util.UserContext;
import cn.community.system.vo.AssociationVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AssociationServiceImpl implements IAssociationService {
    @Autowired
    private AssociationMapper associationMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberVoMapper memberVoMapper;

    @Override
    public void delete(Long id) {
        associationMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Association association) {
        // 参数校验
        // 校验
        AssertUtils.hasLength(association.getNumber(),"编号不能为空！");
        if(associationMapper.checkNumber(association.getNumber())!=null){
            throw new LogicException("该社团编号已经存在！");
        }
        AssertUtils.hasLength(association.getUsername(),"社团名称不能为空！");
        if(associationMapper.selectByName(association.getUsername())!=null){
            throw new LogicException("该社团名称已经存在！");
        }
        AssertUtils.hasLength(association.getPassword(),"密码不能为空！");
        AssertUtils.hasLength(association.getDutyName(),"社团负责人不能为空！");
        AssertUtils.hasLength(association.getDutyMobile(),"社团负责人的联系方式不能为空！");
        if(associationMapper.findByPhone(association.getDutyMobile())!=null){
            throw new LogicException("该联系方式已经存在！");
        }
        // 图片
        if(association.getImgUrl() == ""){
            association.setImgUrl(null);
        }
        // 对加密进行加密（用户名作为盐）
        String password = association.getPassword();
        Md5Hash md5Hash = new Md5Hash(password, association.getUsername());
        // 设置加密的结果
        association.setPassword(md5Hash.toString());
        String name = association.getFounder();
        Member member = memberMapper.selectByName(name);
        if(member != null){
            association.setDutyId(member.getId());
        }
        associationMapper.insert(association);
    }

    @Override
    public Association get(Long id) {
        return associationMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Association> listAll() {
        return associationMapper.selectAll();
    }

    @Override
    public void update(Association association) {
        // 校验
        Long id = association.getId();
        AssertUtils.hasLength(association.getNumber(),"编号不能为空！");
        Association number = associationMapper.checkNumber(association.getNumber());
        if(number != null && number.getId() != id){
            throw new LogicException("该社团编号已经存在！");
        }
        AssertUtils.hasLength(association.getUsername(),"社团名称不能为空！");
        Association name = associationMapper.selectByName(association.getUsername());
        if(name != null && name.getId() != id){
            throw new LogicException("该社团名称已经存在！");
        }
        AssertUtils.hasLength(association.getPassword(),"密码不能为空！");
        Association asso = associationMapper.selectByPrimaryKey(id);
        if(association.getPassword() != asso.getPassword()){
            Md5Hash md5Hash = new Md5Hash(association.getPassword(), association.getUsername());
            // 设置加密的结果
            association.setPassword(md5Hash.toString());
        }
        AssertUtils.hasLength(association.getDutyName(),"社团负责人不能为空！");
        AssertUtils.hasLength(association.getDutyMobile(),"社团负责人的联系方式不能为空！");
        Association phone = associationMapper.findByPhone(association.getDutyMobile());
        if(phone != null && phone.getId() != id){
            throw new LogicException("该联系方式已经存在！");
        }
        // 图片
        if(association.getImgUrl() == ""){
            association.setImgUrl(null);
        }
        // 创建者id
        Member member = memberMapper.selectByName(association.getFounder());
        if(member != null){
            association.setDutyId(member.getId());
        }
        associationMapper.updateByPrimaryKey(association);
    }

    public PageInfo query(QueryObject qo) {
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询结果集
        List<Association> list = associationMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public PageInfo queryMyAssos(AssociationQuery qo) {
        Member member = UserContext.getCurrentMember();
        qo.setMemberId(member.getId());
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询结果集
        List<AssociationVo> list = associationMapper.selectForMyAssoList(qo);
        return new PageInfo(list);
    }

    public PageInfo listAsso(AssociationQuery qo) {
        Long id = UserContext.getCurrentMember().getId();
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询结果集
        List<AssociationVo> list = associationMapper.selectAll2();
        for (AssociationVo associationVo : list) {
            MemberVo memberVo = memberVoMapper.selectByMemberIdAndAssoId(id, associationVo.getId());
            if(memberVo != null){
                associationVo.setIsAdd(memberVo.getIsAgree());
            }else {
                associationVo.setIsAdd(AssociationVo.EXSIST_NO);
            }
        }
        return new PageInfo(list);
    }

    @Override
    public void save2(Association association) {
        // 校验
        AssertUtils.hasLength(association.getNumber(),"编号不能为空！");
        if(associationMapper.checkNumber(association.getNumber())!=null){
            throw new LogicException("该社团编号已经存在！");
        }
        AssertUtils.hasLength(association.getUsername(),"社团名称不能为空！");
        if(associationMapper.selectByName(association.getUsername())!=null){
            throw new LogicException("该社团名称已经存在！");
        }
        AssertUtils.hasLength(association.getPassword(),"密码不能为空！");
        AssertUtils.hasLength(association.getDutyName(),"社团负责人不能为空！");
        AssertUtils.hasLength(association.getDutyMobile(),"社团负责人的联系方式不能为空！");
        if(associationMapper.findByPhone(association.getDutyMobile())!=null){
            throw new LogicException("该联系方式已经存在！");
        }
        // 图片
        if(association.getImgUrl() == ""){
            association.setImgUrl(null);
        }
        // 对加密进行加密（用户名作为盐）
        String password = association.getPassword();
        Md5Hash md5Hash = new Md5Hash(password, association.getUsername());
        // 设置加密的结果
        association.setPassword(md5Hash.toString());
        // 获取用户信息
        Member member = UserContext.getCurrentMember();
        association.setFounder(member.getUsername());
        association.setDutyId(member.getId());
        association.setIsAgree(Association.AGREE_NORMAL);
        associationMapper.insert(association);
    }

    @Override
    public boolean checkPhone(String phone) {
        Association association = associationMapper.findByPhone(phone);
        return association != null;
    }

    @Override
    public void regist(Association association, String rpassword) {
        // 1、接收所有的参数进行校验：非空
        AssertUtils.hasLength(association.getNumber(),"编号不能为空！");
        AssertUtils.hasLength(association.getUsername(),"姓名不能为空！");
        AssertUtils.hasLength(association.getPassword(),"密码不能为空！");
        AssertUtils.hasLength(rpassword,"确认密码不能为空！");
        AssertUtils.hasLength(association.getDutyName(),"社团负责人不能为空！");
        AssertUtils.hasLength(association.getDutyMobile(),"负责人联系方式不能为空！");
        // 2、校验两次密码是否一致
        AssertUtils.isEqual(association.getPassword(),rpassword,"两次的密码不一致！");
        // 3、手机格式和唯一性的校验
        String regex = "^1[3456789]\\d{9}$";
        if (!association.getDutyMobile().matches(regex)){
            throw new LogicException("手机号码格式不正确！");
        }
        if (this.checkPhone(association.getDutyMobile())){
            throw new LogicException("该手机号已经被注册！");
        }
        // 4、用户注册，将用户信息保存到数据库中
        association.setIsAgree(Association.AGREE_NORMAL);
        this.save(association);
    }

    @Override
    public Association userLogin(String username, String password) {
        Association association = associationMapper.selectByNameAndPassword(username, password);
        if (association == null){
            throw new LogicException("账号或密码错误！");
        }
        return association;
    }

    @Override
    public void batchDelete(Long[] ids) {
        associationMapper.deleteBatch(ids);
    }

    @Override
    public Long findIdByName(String association) {
        return associationMapper.findIdByAssociation(association);
    }

    @Override
    public void passOne(Long id, Integer isAgree) {
        associationMapper.passOne(id,isAgree);
    }

    @Override
    public Association getAssociationByUsername(String username) {
        return associationMapper.selectByName(username);
    }

    @Override
    public void importXls(MultipartFile file) throws Exception {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取行的最大索引数
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            Association association = new Association();
            String number = row.getCell(1).getStringCellValue();
            association.setNumber(number);
            association.setUsername(row.getCell(2).getStringCellValue());
            association.setPassword(row.getCell(3).getStringCellValue());
            association.setCharact(row.getCell(4).getStringCellValue());
            association.setSynopsis(row.getCell(5).getStringCellValue());
            double person = row.getCell(6).getNumericCellValue();
            association.setPerson((int)person);
            association.setDutyName(row.getCell(7).getStringCellValue());
            association.setDutyMobile(row.getCell(8).getStringCellValue());
            association.setEmail(row.getCell(9).getStringCellValue());
            association.setTeacher(row.getCell(10).getStringCellValue());
            association.setTeacherMobile(row.getCell(11).getStringCellValue());
            //获取文本格式的单元格内容
            // member.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //获取数值类型的单元格内容
            //double value = row.getCell(2).getNumericCellValue();
            //user.setAge((int)value);
            //调用保存方法
            Md5Hash md5Hash = new Md5Hash(association.getPassword(), association.getUsername());
            // 设置加密的结果
            association.setPassword(md5Hash.toString());
            association.setIsAgree(Association.AGREE_YES);
            associationMapper.insert(association);
        }

    }

    @Override
    public Workbook exportXls() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet(一页纸)
        Sheet sheet = wb.createSheet("社团名单");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("社团编号");
        row.createCell(2).setCellValue("社团名称");
        row.createCell(3).setCellValue("创始人");
        row.createCell(4).setCellValue("性质");
        row.createCell(5).setCellValue("简介");
        row.createCell(6).setCellValue("人数");
        row.createCell(7).setCellValue("负责人");
        row.createCell(8).setCellValue("联系方式");
        row.createCell(9).setCellValue("邮箱");
        row.createCell(10).setCellValue("指导老师");
        row.createCell(11).setCellValue("指导老师电话");
        row.createCell(12).setCellValue("每年的活动总个数");
        row.createCell(13).setCellValue("每年的活动总天数");
        //查询员工数据
        List<Association> associations = associationMapper.selectAll();
        for (int i = 0; i < associations.size(); i++) {
            Association association = associations.get(i);
            //创建行(每个员工就是一行)
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(i+1);
            row.createCell(1).setCellValue(association.getNumber());
            row.createCell(2).setCellValue(association.getUsername());
            row.createCell(3).setCellValue(association.getFounder());
            row.createCell(4).setCellValue(association.getCharact());
            row.createCell(5).setCellValue(association.getSynopsis());
            row.createCell(6).setCellValue(association.getPerson());
            row.createCell(7).setCellValue(association.getDutyName());
            row.createCell(8).setCellValue(association.getDutyMobile());
            row.createCell(9).setCellValue(association.getEmail());
            row.createCell(10).setCellValue(association.getTeacher());
            row.createCell(11).setCellValue(association.getTeacherMobile());
            Integer activityNumber = association.getActivityNumber();
            if(activityNumber == null){
                association.setActivityNumber(0);
            }
            row.createCell(12).setCellValue(association.getActivityNumber());
            Double day = association.getDay();
            if(day == null){
                association.setDay(0.0);
            }
            row.createCell(13).setCellValue(association.getDay());
        }
        return wb;
    }

    @Override
    public PageInfo getFounderByDutyId(QueryObject qo) {
        Member member = UserContext.getCurrentMember();
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询结果集
        List<Association> list = associationMapper.getFounderByDutyId(member.getId());
        return new PageInfo(list);
    }

    @Override
    public void myUpdate(Association association) {
        String number = association.getNumber();
        String password = association.getPassword();
        String username = association.getUsername();
        AssertUtils.hasLength(number,"编号不能为空！");
        Association checkNumber = associationMapper.checkNumber(number);
        if (checkNumber != null && checkNumber.getId() != association.getId()){
            throw new LogicException("该编号已被注册！");
        }
        AssertUtils.hasLength(username,"社团名称不能为空！");
        Association selectByName = associationMapper.selectByName(username);
        if (selectByName != null && selectByName.getId() != association.getId()){
            throw new LogicException("该社团名称已被注册！");
        }
        AssertUtils.hasLength(password,"密码不能为空！");
        Association asso = associationMapper.selectByPrimaryKey(association.getId());
        // 密码加密
        if(!asso.getPassword().equals(password)){ // 密码改变时才加密
            Md5Hash md5Hash = new Md5Hash(password, username);
            association.setPassword(md5Hash.toString());
        }
        // 检查负责人的手机号是否存在
        String phone = association.getDutyMobile();
        AssertUtils.hasLength(phone,"负责人的联系方式不能为空！");
        String mobile = asso.getDutyMobile();
        if(!phone.equals(mobile)){
            if (associationMapper.findByPhone(phone) != null){
                throw new LogicException("该联系方式已被注册！");
            }
        }
        // 创始人的id
        List<Association> associations =  associationMapper.findFounderId(association.getFounder());
        if(associations != null){
            association.setDutyId(associations.get(0).getId());
        }
        // 图片
        if(association.getImgUrl() == ""){
            association.setImgUrl(null);
        }
        associationMapper.myUpdate(association);
    }

    @Override
    public void updateActivityNumberAndDay(Association association) {
        associationMapper.updateActivityNumberAndDay(association);
    }
}
